package com.example.demotencentbigdata.tbds;

import com.example.demotencentbigdata.api.JDBCApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Component
public class TBDS implements JDBCApi {
    @Override
    public List<HashMap<String, Object>> testQuery(Connection connection, String querySql) throws SQLException {
        List<HashMap<String,Object>> datas = new ArrayList<>();
        // Class.forName("");
        try(
                PreparedStatement preparedStatement = connection.prepareStatement(querySql);
                ResultSet resultSet = preparedStatement.executeQuery();) {
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();

            while (resultSet.next()) {
                HashMap<String,Object> data = new HashMap<>();
                for (int i = 0; i < columnCount; i++) {
                    data.put(metaData.getColumnName(i+1),resultSet.getObject(i+1));
                }
                datas.add(data);
            }
            return datas;
        }
    }

    @Override
    public Connection getConnect(String url, String userName, String passWd) throws SQLException {
        try {
            Class.forName("org.apache.hive.jdbc.HiveDriver");
        return DriverManager.getConnection(url,userName,passWd);
        } catch (ClassNotFoundException e) {
            log.error("获取Hive连接失败",e);
            throw new RuntimeException("获取hive连接失败！");
        }
    }

    @Override
    public int update(Connection connection, String updateSql) throws SQLException {
        try(
                PreparedStatement preparedStatement = connection.prepareStatement(updateSql)) {
            return preparedStatement.executeUpdate();
        }
    }
}
